<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Weixin extends WX_Controller {

    public $token;
    public $fromuser;
    public $touser;
    public $content;
    public $back_key;
    public $event_key;
    public $MediaId;

    public function index() {
        $this->token = $_GET['token'];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $tmpArr = array($this->token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        // echo $_GET['token'];
        if ($tmpStr != $signature) {
            //exit();
        }
        if ($_GET['echostr']) {

//            $this->db->update(array('_id'=>$mongoid),array('$set'=>array('tokens.weixin.status'=>1)));
            echo $_GET['echostr'];
            exit;
        }
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (empty($postStr)) {
            exit();
        }

        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $this->fromuser = (string) $postObj->FromUserName;
        $this->touser = $postObj->ToUserName;
        $this->content = trim($postObj->Content);
        $msg_type = trim($postObj->MsgType);
        $this->event = trim($postObj->Event);

//
////引入记录函数
//        require_once(dirname(__FILE__).'/record.func.php');
//        user_record();
//
//

        if ($msg_type == 'event') {  //事件类型
            $event = $postObj->Event;
            if ($event == 'subscribe') {
                // $this->save_wx_user();
                $this->even_respon();
            }
            if ($event == 'CLICK') {
                $this->event_key = $postObj->EventKey;
                // $this->respon_customer();
//				if($this->is_user_customer()=="1")
//				{
//					$this->respon_text("你现在正在使用客服系统，请说话！如退出客服系统请输入X或退出。");
//				}else{
//					$this->save_wx_user_customer();
//					$this->respon_text("欢迎你使用客服系统，如退出客服系统请输入X或退出。");
//				}
                $this->menu_respon();
            }
            if ($event == 'unsubscribe') {
                $logid = $this->save_user_log("unsubscribe", '', "", "取消关注", '1', '0');
                $this->update_wx_user();
            }
        } else if ($msg_type == 'text') {  //文本类型
            if ($this->content == "客服") {
                if ($this->is_user_customer() == "1") {
                    $this->respon_text("你现在正在使用客服系统，请说话！如退出客服系统请输入X或退出。");
                } else {
                    $this->save_wx_user_customer();
                    $this->respon_text("欢迎你使用客服系统，如退出客服系统请输入X或退出。");
                }
            } else {
                if ($this->is_user_customer() == "1") {
                    if (strtoupper($this->content) == "X" or $this->content == "退出") {
                        $this->update_wx_user_customer();
                        $this->respon_text("谢谢你使用客服系统！");
                    } else {

                        $r = $this->save_user_customer_log($msg_type, $this->content);
                        if (!$r) {
                            $this->respon_text("信息发送失败，请稍后再试。");
                        } else {
                            $this->respon_text("你现在正在与客服沟通交流中,客服人员稍后回复你的问题，请耐心等待！！");
                        }
                    }
                } else {
                    $this->user_respon();
                }
            }
        } else if ($msg_type == 'image') {  //图片类型
            $picUrl = $postObj->PicUrl;  //图片地址
            if ($this->is_user_customer() == "1") {
                $logid = $this->save_user_customer_log($msg_type, UrlDecode($picUrl));
            } else {
                $logid = $this->save_user_log("", "", "", UrlDecode($picUrl), '1', '0');
            }
            // include_once(dirname(__FILE__).'/image.inc.php');
//            $sql = $this->db->query("select `type`,pid,text from `unknow` where token = '$this->token'");
//            $unknow_result = $sql->row_array();
//            if($unknow_result)
//            {
//                $this->respon_type($unknow_result,$logid,"unknow");
//            }
        } else if ($msg_type == 'link ') {  //链接
            $picUrl = $postObj->Url;  //图片地址
            if ($this->is_user_customer() == "1") {
                $logid = $this->save_user_customer_log($msg_type, $picUrl);
            } else {
                $logid = $this->save_user_log("", "", "", $picUrl, '1', '0');
            }
//            $sql = $this->db->query("select `type`,pid,text from `unknow` where token = '$this->token'");
//            $unknow_result = $sql->row_array();
//            if($unknow_result)
//            {
//                $this->respon_type($unknow_result,$logid,"unknow");
//            }
            // include_once(dirname(__FILE__).'/image.inc.php');
        } else if ($msg_type == 'voice') {  //语音
            //公众平台或暂未开放语音的获取，没有提供语音地址，因此处先省略。
            $MediaId = trim($postObj->MediaId);  //图片地址
            if ($this->is_user_customer() == "1") {
                $this->respon_text("客服系统暂不支持你发送的格式" . $msg_type);
                // $logid=$this->save_user_customer_log($msg_type,$MediaId);
            } else {
                $logid = $this->save_user_log("voice", "", "", $MediaId, '1', '0');
            }

//        }else if($msg_type == 'location')  //地理位置
//        {
//            $location_X = $postObj->Location_X;  //维度
//            $location_Y = $postObj->Location_Y;  //经度
//            $label = $postObj->Label ;  //地理信息
//			if($this->is_user_customer()=="1")
//			{
//	  		    $logid=$this->save_user_customer_log($msg_type,$label);
//			}
            // include_once(dirname(__FILE__).'/location.inc.php');
//        }
        } else {
            if ($this->is_user_customer() === "1") {
                // $this->respon_text($msg_type);
                $this->respon_text("客服系统暂不支持你发送的格式" . $msg_type);
            } else {
                $this->respon_text("系统暂不支持你发送的格式");
            }
        }
//        else if($msg_type == 'location')  //地理位置
//        {
//            $location_X = $postObj->Location_X;  //维度
//            $location_Y = $postObj->Location_Y;  //经度
//            $label = $postObj->Label ;  //地理信息
//            include_once(dirname(__FILE__).'/location.inc.php');
//        }
//        else if($msg_type == 'video')  //视频
//        {
//            //公众平台或暂未开放视频的获取，没有提供视频地址，因此处先省略。
//        }
//        else if($msg_type == 'voice')  //语音
//        {
//            //公众平台或暂未开放语音的获取，没有提供语音地址，因此处先省略。
//        }
    }

    /*
      function downloadWeixinFile($url)
      {
      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_NOBODY, 0);
      //只取body头
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      $package = curl_exec($ch);
      $httpinfo = curl_getinfo($ch);
      curl_close($ch);
      $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));
      return $imageAll;
      }
      function saveWeixinFile($filename, $filecontent) {
      $local_file = fopen($filename, 'w');
      if (false !== $local_file)
      {
      if (false !== fwrite($local_file, $filecontent))
      {
      fclose($local_file);
      }
      }
      }
     */
    /*
     * $type记录操作的每一个表名
     */

    public function save_user_log($type, $primary_id, $sub_id, $content, $oper_type, $logid) {
//oper_type１表示用户提问的日志，２表示系统回复的日志
        $this->db->insert("log", array("log_id" => $logid, "sign" => $oper_type, "fromuser" => $this->fromuser, 'token' => $this->token, 'type' => $type, 'content' => $content, 'primary_id' => $primary_id, 'sub_id' => $sub_id, 'ctime' => date("Y-m-d H:i:s")));
        return $this->db->insert_id();
    }

    /*
     * 保存客服日志信息
     */

    public function save_user_customer_log($type, $content) {

        $r = $this->db->insert("customer_log", array("fromuser" => $this->fromuser, 'status' => 0, 'token' => $this->token, 'type' => $type, 'content' => $content, 'ctime' => date("Y-m-d H:i:s")));
        return $r;
    }

//关键字模糊查询判断
// $keyarr关键字数据　$cont用户输入的关键字
    function keyword_sel($res, $cont) {
        $keyword_result = array();
        foreach ($res as $row) {
            $keyword = explode("|", $row['keyword']);
            $sel_sign = $this->sel_word($keyword, $cont);
//有匹配数据时
            if ($sel_sign) {
                $keyword_result['id'] = $row['id'];
                $keyword_result['pid'] = $row['pid'];
                $keyword_result['type'] = $row['type'];
                $keyword_result['text'] = $row['text'];
                return $keyword_result;
            } else {
//无匹配数据时下一个数组中对应的关键字
                $sel_sign = $this->sel_word($keyword, $cont);
            }
        }
        return $sel_sign;
    }

//判断关键字
    function sel_word($keyword, $cont) {
        for ($e = 1; $e < count($keyword) - 1; $e++) {
            while (strstr($cont, $keyword[$e])) {
                return true;
            }
        }
        return false;
    }

// 菜单事件处理
    function menu_respon() {
//关注时获取用户信息
//获取token
//关注时获取用户信息
// $this->respon_text("select `type`,pid,text from `button` where id = '$this->event_key' ");
        $sql = $this->db->query("select * from `button` where id = '$this->event_key' ");
        $subscribe = $sql->row_array();
        if ($subscribe) {
            if ($subscribe['type'] == 4) {//互动时把菜单的名称作为关键字进行流程操作
                // $this->content=$subscribe['key_word'];
                // $this->update_step($subscribe['pid'],'0');
                $sql = $this->db->query("select text from processes where id = '" . $subscribe['pid'] . "'");
                $pre_result = $sql->row_array();
                $logid = $this->save_user_log("processes", $subscribe['pid'], "", $subscribe['key_name'], '1', '0');
                $this->update_step($subscribe['pid']);
                $this->save_user_log("processes", $subscribe['pid'], "", $pre_result['text'], '2', $logid);
                $this->respon_text($pre_result['text']);
            } else {
                $logid = $this->save_user_log("button", $this->event_key, "", $subscribe['key_name'], '1', '0');
                $this->respon_type($subscribe, $logid, "button");
            }
        }
    }

    //事件处理
    function even_respon() {
        if ($this->event == 'subscribe') {
//关注时获取用户信息
//获取token
//关注时获取用户信息
            $sql = $this->db->query("select `type`,pid,text from `subscribe` where token = '$this->token' ");
            $subscribe = $sql->row_array();
            if ($subscribe) {
                $logid = $this->save_user_log("subscribe", '', "", "关注", '1', '0');
                $this->respon_type($subscribe, $logid, "subscribe");
            }
        }
    }

    function user_respon() {
        $sql = $this->db->query("select * from user_step where fromuser = '$this->fromuser'");
        $step = $sql->row_array();
        $this->back_key = '0';

        // $this->respon_image("spBx_kEv9Wh9GniCvgAqkGFAjOEXyRyNjvIW4HYFIz5IlUv1pl32YnSo691ScZqO");
        //判断是否已进入互动流程
        if (!$step['primary_id'] || $step['time'] < time() - 600) {//没有进入，判断关键词
            // $this->respon_text("select `type`,pid,text from keywords where token = '$this->token' and keyword like '%|$this->content|%' ");
            $sql = $this->db->query("select id,`type`,pid,text,keyword from keywords where token = '$this->token' order by id");
            $keyword_result = $sql->result_array();
// 关键字判断，如果查询到相关关键字返回对应值的数组，或者返回假
            $return_value = $this->keyword_sel($keyword_result, $this->content);
            if ($return_value) {
                $logid = $this->save_user_log("keywords", "", "", $this->content, '1', '0');
                $this->respon_type($return_value, "", "keywords");
            } else {
                $sql = $this->db->query("select `type`,pid,text from `unknow` where token = '$this->token'");
                $unknow_result = $sql->row_array();
                if ($unknow_result) {
                    $logid = $this->save_user_log("unknow", "", "", $this->content, '1', '0');
                    $this->respon_type($unknow_result, $logid, "unknow");
                }
            }
//            if($keyword_result)
//            {
//				$logid=$this->save_user_log("keywords","","",$this->content,'1','0');
//                $this->respon_type($keyword_result,"");
//            }
//            else
//            {
//                $sql = $this->db->query("select `type`,pid,text from `unknow` where token = '$this->token'");
//                $unknow_result = $sql->row_array();
//                if($unknow_result)
//                {
//					$logid=$this->save_user_log("unknow","","",$this->content,'1','0');
//                    $this->respon_type($unknow_result,$logid);
//                }
//
//            }
//原来的模糊查询
//            $sql = $this->db->query("select `type`,pid,text from keywords where token = '$this->token' and $this->content like '%|'.keyword.'|%' ");
//            $keyword_result = $sql->row_array();
//            if($keyword_result)
//            {
//				$logid=$this->save_user_log("keywords","","",$this->content,'1','0');
//                $this->respon_type($keyword_result,"");
//            }
//            else
//            {
//                $sql = $this->db->query("select `type`,pid,text from `unknow` where token = '$this->token'");
//                $unknow_result = $sql->row_array();
//                if($unknow_result)
//                {
//					$logid=$this->save_user_log("unknow","","",$this->content,'1','0');
//                    $this->respon_type($unknow_result,$logid);
//                }
//
//            }
        } else {//已进入流程
            //判断是否已进入子流程
            if (!$step['sub_id']) {//没有进入
                if ($this->content == $this->back_key) {//判断是否返回
                    $this->update_step();
                    $logid = $this->save_user_log("processes", "0", "0", "退出流程", '1', '0');
                    $this->respon_text('已退出互动流程');
                    $this->save_user_log("processes", "0", "0", "退出流程", '2', $logid);
                }

                $sql = $this->db->query("select id,`type`,pid,text from processes_sub where primary_id = '$step[primary_id]' and keyword like '%$this->content%' ");

                $sub_result = $sql->row_array();
                if ($sub_result) {
                    $logid = $this->save_user_log("processes", $step['primary_id'], $sub_result['id'], $this->content, '1', '0');
                    $this->update_step($step['primary_id'], $sub_result['id']);
                    $this->respon_type($sub_result, $logid, "processes");
                } else {//没有匹配的
                    $sql = $this->db->query("select `type`,pid,text from `unknow` where token = '$this->token' ");
                    $unknow_result = $sql->row_array();
                    if ($unknow_result) {
                        $logid = $this->save_user_log("unknow", "", "", $this->content, '1', '0');
                        $this->respon_type($unknow_result, $logid, "unknow");
                    }
                }
            } else {//已进入
                if ($this->content == $this->back_key) {//判断是否返回
                    $sql = $this->db->query("select primary_id,pre_id from processes_sub where id = '$step[sub_id]'");
                    $sub_result = $sql->row_array();
                    if ($sub_result['pre_id']) {
                        $sql = $this->db->query("select `type`,pid,text from processes_sub where id = '$sub_result[pre_id]'");
                        $pre_result = $sql->row_array();
                        $logid = $this->save_user_log("processes", $step['primary_id'], $sub_result['id'], $this->content, '1', '0');
                        $this->update_step($step['primary_id'], $sub_result['pre_id']);
                        $this->respon_type($pre_result, $logid, "processes");
                    } else {
                        $sql = $this->db->query("select text from processes where id = '$sub_result[primary_id]'");
                        $pre_result = $sql->row_array();
                        $logid = $this->save_user_log("processes", $step['primary_id'], "", $this->content, '1', '0');
                        $this->update_step($step['primary_id']);
                        $this->respon_text($pre_result['text']);
                        $this->save_user_log("processes", $step['primary_id'], "", $pre_result['text'], '2', $logid);
                    }
                }
                // $this->respon_text("select id,`type`,pid,text from processes_sub where pre_id = '$step[sub_id]' and keyword like '%$this->content%' ");

                $sql = $this->db->query("select id,`type`,pid,text from processes_sub where pre_id = '$step[sub_id]' and keyword like '%$this->content%' ");
                $sub_result = $sql->row_array();
                if ($sub_result) {
                    $logid = $this->save_user_log("processes", $step['primary_id'], $sub_result['id'], $this->content, '1', '0');
                    $this->update_step($step['primary_id'], $sub_result['id']);
                    $this->respon_type($sub_result, $logid, "processes");
                } else {//没有匹配的
                    $sql = $this->db->query("select `type`,pid,text from `unknow` where token = '$this->token' ");
                    $unknow_result = $sql->row_array();
                    if ($unknow_result) {
                        $logid = $this->save_user_log("unknow", "", "", $this->content, '1', '0');
                        $this->respon_type($unknow_result, $logid, "unknow");
                    }
                }
            }
        }
    }

    /*
     * 选择回复类型
     * @param $result array 说明：type,pid,text
     *    type：1 = 普通文本回复  直接使用text
     *          2 = 单图
     *          3 = 多图
     * 			４= 互动
     * 　　　　　　5：图片
     * 　　　　　　６：音频
     * 　　　　　　７：视频
     *    pid: 对应回复类型的id
     *    text: 直接回复的文本
     */

    function respon_type($result, $logid, $oper_type) {
        $type_arr = array(4 => 'processes', '2' => 'news', '3' => 'news', 5 => 'content', 6 => 'content', 7 => 'content');
        $table = $type_arr[$result['type']];
        switch ($result['type']) {
            case 1:
                $rr = $this->save_user_log($oper_type, "", "", $result['text'], '2', $logid);
                $this->respon_text($result['text']);
                break;
            case 2:
            case 3:
                $rr = $this->save_user_log($table, $result['pid'], "", "", '2', $logid);
                $sql = $this->db->query("select * from $table where list_id = '$result[pid]' order by id");
                $news = $sql->result_array();
                $this->respon_pics($news);
                break;
            case 4:
                $sql = $this->db->query("select id,text from $table where id = '$result[pid]'");
                $process = $sql->row_array();
                $this->save_user_log($table, $result['pid'], "", $process['text'], '2', $logid);
                $this->update_step($process['id']);
                $this->respon_text($process['text']);
                break;
            case 5:
                $sql = $this->db->query("select * from $table where id = '$result[pid]'");
                $res = $sql->row_array();
//				if($res['ctime']<time()-259200)//超过３天重新上传文件
//				{
//					$new_media_id=$this->load_Mediafile($this->token,$res['id'],"image");
//	                $this->respon_image($new_media_id);
//				}else{
                $this->save_user_log($table, $result['pid'], "", $res['url'], '2', $logid);
                $this->respon_image($res['wx_id']);
//				}
                break;
            case 6:
                $sql = $this->db->query("select * from $table where id = '$result[pid]'");
                $res = $sql->row_array();
                $this->save_user_log($table, $result['pid'], "", $res['url'], '2', $logid);
//				if($res['ctime']<time()-259200)//超过３天重新上传文件
//				{
//					$new_media_id=$this->load_Mediafile($this->token,$res['id'],"voice");
//	                $this->respon_voice($new_media_id);
//				}else{
                $this->respon_voice($res['wx_id']);
//				}
                break;
            case 7:
                $sql = $this->db->query("select * from $table where id = '$result[pid]'");
                $res = $sql->row_array();
                $this->save_user_log($table, $result['pid'], "", $res['url'], '2', $logid);
//				if($res['ctime']<time()-259200)//超过３天重新上传文件
//				{
//					$new_media_id=$this->load_Mediafile($this->token,$res['id'],"video");
//	                $this->respon_video($new_media_id);
//				}else{
                $this->respon_video($res['wx_id']);
// 				}
                break;
        }
    }

    /*
      function respon_type($result)
      {
      $type_arr = array(2=>'processes','news',5=>'content');
      $table = $type_arr[$result['type']];
      switch ($result['type'])
      {
      case 1:
      $this->respon_text($result['text']);
      break;
      case 2:
      $sql = $this->db->query("select id,text from $table where id = '$result[pid]'");
      $process = $sql->row_array();
      $this->update_step($process['id']);
      $this->respon_text($process['text']);
      break;
      case 3:
      $sql = $this->db->query("select title,description,picurl,url from $table where list_id = '$result[pid]'");
      $news = $sql->result_array();
      $this->respon_pics($news);
      break;
      case 5:
      $sql = $this->db->query("select * from $table where id = '$result[pid]'");
      $res=$sql->row_array();
      if($res['time']<time()-259200)//超过３天重新上传文件
      {
      $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$wx_token&type=$type";
      $post_data = array (
      "media" => "@".$res['url']
      );
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
      $output = curl_exec($ch);
      $file_json=json_decode($output);
      $r=$this->db->update('content', array('wx_id'=>$file_json->media_id,'ctime'=>$file_json->created_at), "id = $content_id ");
      curl_close($ch);
      $this->respon_image($file_json->media_id);
      }else{
      $this->respon_image($res['wx_id']);
      }

      break;

      }


      }

     */

    /*
     * 更新用户流程记录
     * @param $primary_id int 主流程id
     * @param $sub_id int  子流程id
     */

    function update_step($primary_id = 0, $sub_id = 0) {
        $sql = $this->db->query("select fromuser from user_step where fromuser = '$this->fromuser' ");
        $step = $sql->row_array();
        if ($step) {
            $this->db->update("user_step", array('primary_id' => $primary_id, 'sub_id' => $sub_id, 'time' => time()), "fromuser = '$this->fromuser'");
            // $this->respon_text($primary_id."####".$sub_id."*****".$this->fromuser);
        } else {
            $this->db->insert("user_step", array("fromuser" => $this->fromuser, 'primary_id' => $primary_id, 'sub_id' => $sub_id, 'time' => time()));
        }
    }

    function getWxToken($token) {
        $sql = $this->db->query("select * from token where token='" . $token . "' and expires_in >'" . (time() - 120) . "' ");
        $num = $sql->num_rows();
        $res = $sql->row_array();
        $err = 'err:';
        if ($num > 0) {
            return $res['access_token'];
        } else {
            $sql_open = $this->db->query("select * from token where token = '$token' ");
            $opdata = $sql_open->row_array();
            $wx = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $opdata['appid'] . '&secret=' . $opdata['appsecret']);
            $token_json = json_decode($wx);
            $access_token = $token_json->access_token;

            $this->db->update("token", array("access_token" => $token_json->access_token, "expires_in" => time()), "token = '$token'");
            return $token_json->access_token;
        }
    }

    /*
     * 关注时保存关注者的信息
     */

    function save_wx_user() {
        $WxToken = $this->getWxToken($this->token);
        $fromuser = $this->fromuser;
        $uinfo_t = file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $WxToken . "&openid=" . $fromuser . "&lang=zh_CN");
        $uinfo = json_decode($uinfo_t);

        $openid = $uinfo->openid;
        $nickname = $uinfo->nickname;
        $headimgurl = $uinfo->headimgurl;
        $sex = $uinfo->sex;
        $city = $uinfo->city;
        $country = $uinfo->country;
        $province = $uinfo->province;
        $subscribe_time = $uinfo->subscribe_time;
        $unionid = $uinfo->unionid;
        $sql = $this->db->query("select * from wx_user where userid='" . $openid . "'");
        $num = $sql->num_rows();
        if ($num > 0) {
            $this->db->query("update wx_user set subscribe_sign='1',username='$nickname',pic='$headimgurl',token='" . $this->token . "',sex='$sex',city='$city',country='$country',province='$province',subscribe_time='$subscribe_time',unionid='$unionid' where userid = '$openid' ");
        } else {
            $this->db->insert("wx_user", array("subscribe_sign" => 1, "username" => $nickname, 'userid' => $openid, 'pic' => $headimgurl, 'token' => $this->token, 'sex' => $sex, 'city' => $city, 'country' => $country, 'province' => $province, 'subscribe_time' => $subscribe_time, 'unionid' => $unionid, 'gtime' => date("Y-m-d H:i:s")));
            $userid = $this->db->insert_id();
            $this->db->insert("group_user", array("group_id" => 0, 'user_id' => $userid, 'gtime' => date("Y-m-d H:i:s")));
        }
    }

    /*
     * 取消关注时修改用户的标识并记录下取消关注的时间
     */

    function update_wx_user() {
        $openid = $this->fromuser;
        $this->db->query("update wx_user set subscribe_sign='2',unsubscribe_time='" . date("Y-m-d H:i:s") . "' where userid = '$openid' ");
    }

    function save_wx_user_customer() {
        $fromuser = $this->fromuser;
        $sql = $this->db->query("select * from wx_user_customer where userid='" . $fromuser . "'");
        $num = $sql->num_rows();
        if ($num > 0) {
            $this->db->query("update wx_user_customer set status='0',unlink_time='',link_time='" . date("Y-m-d H:i:s") . "' where userid = '" . $fromuser . "' ");
        } else {
            $WxToken = $this->getWxToken($this->token);
            $uinfo_t = file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $WxToken . "&openid=" . $fromuser . "&lang=zh_CN");
            $uinfo = json_decode($uinfo_t);
            $openid = $uinfo->openid;
            $nickname = $uinfo->nickname;
            $headimgurl = $uinfo->headimgurl;
            $sex = $uinfo->sex;
            $city = $uinfo->city;
            $country = $uinfo->country;
            $province = $uinfo->province;
            $subscribe_time = $uinfo->subscribe_time;
            $unionid = $uinfo->unionid;

            $this->db->insert("wx_user_customer", array("status" => 0, "username" => $nickname, 'userid' => $openid, 'pic' => $headimgurl, 'token' => $this->token, 'sex' => $sex, 'city' => $city, 'country' => $country, 'province' => $province, 'subscribe_time' => $subscribe_time, 'unionid' => $unionid, 'gtime' => date("Y-m-d H:i:s"), 'link_time' => date("Y-m-d H:i:s")));
        }
    }

    function update_wx_user_customer() {
        $openid = $this->fromuser;
        $this->db->query("update wx_user_customer set status='2',unlink_time='" . date("Y-m-d H:i:s") . "' where userid = '$openid' ");
    }

    function is_user_customer() {
        $fromuser = $this->fromuser;
        $sql = $this->db->query("select * from wx_user_customer where userid='" . $fromuser . "' and status='0'");
        $num = $sql->num_rows();
        if ($num > 0) {
            return 1;
        } else {
            return 2;
        }
    }

    function show_error($errno, $errstr) {
        global $err;
        if ($errno == E_ERROR)
            $err .= $errstr . " || ";
    }

    function respon_customer() {
        // $contentStr = $this->delhtml(trim($contentStr));
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
        $resultStr = sprintf($textTpl, $this->fromuser, $this->touser, time(), "transfer_customer_service");
        //recordUserBehavior($contentStr);
        echo $resultStr;
//    $CI->db->insert("",array('user_account'=>$user_account,'from_user'=>$fromUsername,'text'=>$contentStr,'time'=>time(),'user_reply'=>1));
        exit();
    }

    /*
      function update_step($primary_id=0,$sub_id=0)
      {
      $sql = $this->db->query("select fromuser from user_step where fromuser = '$this->fromuser' ");
      $step = $sql->row_array();
      if($step)
      $this->db->update("user_step",array('primary_id'=>$primary_id,'sub_id'=>$sub_id,'time'=>time()),"fromuser = '$this->fromuser'");
      else
      $this->db->insert("user_step",array("fromuser" => $this->fromuser,'primary_id'=>$primary_id,'sub_id'=>$sub_id,'time'=>time()));

      }
     */

    function respon_text($contentStr) {
        $contentStr = $this->delhtml(trim($contentStr));
        $textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					<FuncFlag>0</FuncFlag>
					</xml>";
        $resultStr = sprintf($textTpl, $this->fromuser, $this->touser, time(), "text", $contentStr);
        //recordUserBehavior($contentStr);
        echo $resultStr;
//    $CI->db->insert("",array('user_account'=>$user_account,'from_user'=>$fromUsername,'text'=>$contentStr,'time'=>time(),'user_reply'=>1));
        exit();
    }

    function respon_pics($news_list) {
        $countitem = count($news_list);
        $Tpl = '';
        foreach ($news_list as $news) {
//            $Tpl .= "<item><Title><![CDATA[".$news['title']."]]></Title> <Description><![CDATA[".$news['description']."]]></Description><PicUrl><![CDATA[".$news['picurl']."]]></PicUrl><Url><![CDATA[".$news['url']."]]></Url></item>";
            if ($news['type'] == 1) {
                $Tpl .= "<item><Title><![CDATA[" . $news['title'] . "]]></Title> <Description><![CDATA[" . $news['description'] . "]]></Description><PicUrl><![CDATA[" . $news['picurl'] . "]]></PicUrl><Url><![CDATA[" . $news['content_url'] . "&openid=" . $this->fromuser . "&gzh=" . $this->token . "&token=" . $this->token . "]]></Url></item>";
            } else {
                //$Tpl .= "<item><Title><![CDATA[".$news['title']."]]></Title> <Description><![CDATA[".$news['description']."]]></Description><PicUrl><![CDATA[".$news['picurl']."]]></PicUrl><Url><![CDATA[".$news['news_url']."]]></Url></item>";
                $Tpl .= "<item><Title><![CDATA[" . $news['title'] . "]]></Title> <Description><![CDATA[" . $news['description'] . "]]></Description><PicUrl><![CDATA[" . $news['picurl'] . "]]></PicUrl><Url><![CDATA[" . $news['news_url'] . "&openid=" . $this->fromuser . "&gzh=" . $this->token . "&token=" . $this->token . "]]></Url></item>";
            }
        }
        $newsTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<ArticleCount>%s</ArticleCount>
					<Articles>" . $Tpl . "</Articles>
					<FuncFlag>0</FuncFlag>
					</xml>";
        $resultStr = sprintf($newsTpl, $this->fromuser, $this->touser, time(), "news", $countitem);
        //recordUserBehavior($resultStr);
        echo $resultStr;

        exit();
    }

    function respon_image($msgid) {
        $newsTpl = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[image]]></MsgType>
				<Image>
				<MediaId><![CDATA[%s]]></MediaId>
				</Image>
				</xml>";
        $resultStr = sprintf($newsTpl, $this->fromuser, $this->touser, time(), $msgid);
        echo $resultStr;

        exit();
    }

    function respon_voice($msgid) {
        $newsTpl = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[voice]]></MsgType>
				<Voice>
				<MediaId><![CDATA[%s]]></MediaId>
				</Voice>
				</xml>";
        $resultStr = sprintf($newsTpl, $this->fromuser, $this->touser, time(), $msgid);
        echo $resultStr;

        exit();
    }

    function respon_video($msgid) {
        $Tpl = "<MediaId><![CDATA[" . $msgid . "]]></MediaId>
				<Title></Title>
				<Description></Description>";
        $newsTpl = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[video]]></MsgType>
				<Video>" . $Tpl . "
				</Video>
				</xml>";
        $resultStr = sprintf($newsTpl, $this->fromuser, $this->touser, time(), $msgid);
        echo $resultStr;

        exit();
    }

    /*
     * 根据不同的多媒体类型
     */

    function load_Mediafile($token, $type, $id) {
        $wx_token = $this->getWxToken($token);
        $sql = $this->db->query("select * from content where id = '" . $id . "'");
        $res = $sql->row_array();

        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$wx_token&type=$type";
        $post_data = array(
            "media" => "@" . $res['url']
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        $file_json = json_decode($output);
        $r = $this->db->update('content', array('wx_id' => $file_json->media_id, 'ctime' => $file_json->created_at), "id = $id ");
        curl_close($ch);
        return $file_json->media_id;
    }

    function delhtml($str) {   //清除HTML标签
        $st = -1; //开始
        $et = -1; //结束
        $stmp = array();
        $stmp[] = "&nbsp;";
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            $ss = substr($str, $i, 1);
            if (ord($ss) == 60) { //ord("<")==60
                $st = $i;
            }
            if (ord($ss) == 62) { //ord(">")==62
                $et = $i;
                if ($st != -1) {
                    $stmp[] = substr($str, $st, $et - $st + 1);
                }
            }
        }
        $str = str_replace($stmp, "", $str);
        return $str;
    }

    function _upload($field_name) {
        $error = "";
        $config['upload_path'] = '../uploads/voice/'; //文件上传路径
        $config['filenametype'] = date("Ymd-His"); //重命名文件名
        $config['max_size'] = 55000000; //允许上传文件大小的最大值
        $config['allowed_types'] = 'mp3|wma|wav|amr';
        $this->upload->initialize($config);
        if ($this->upload->do_upload($field_name)) {
            return $this->upload->data();
        } else {
            foreach ($this->upload->error_msg as $v) {
                $error.= addslashes($v) . '\n';
            }
            showmsg($error);
            die;
        }
    }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */